package com.changge.common.core.utils;

import cn.hutool.core.lang.Snowflake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 雪花算法生成ID工具类
 *
 * @author zhangrongkang
 * @since 2023/3/7
 */
@Slf4j
@Component
public class IdUtil {

    /**
     * 数据中心ID
     */
    @Value("${system.snowflake.datacenterId}")
    private long datacenterId;

    /**
     * 机器ID
     */
    @Value("${system.snowflake.workerId}")
    private long workerId;


    /**
     * IP内存查询对象
     */
    private final Snowflake snowflake = new Snowflake(workerId, datacenterId);

    /**
     * 根据雪花算法生成ID
     *
     * @return 返回生成的ID
     */
    public Long nextId() {
        return snowflake.nextId();
    }

    /**
     * 获取随机UUID
     *
     * @return 随机UUID
     */
    public static String randomUuId() {
        return UUID.randomUUID().toString();
    }

    /**
     * 简化的UUID，去掉横线
     *
     * @return 简化的UUID
     */
    public static String simpleUuId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static void main(String[] args) {
        IdUtil idUtil = new IdUtil();
        for (int i = 0; i < 10; i++) {
            System.out.println(idUtil.nextId());
        }
    }

}
